package com.epsoft.fabric.demo;

import java.util.ArrayList;
import java.util.List;

import org.hyperledger.fabric.contract.Context;
import org.hyperledger.fabric.contract.ContractInterface;
import org.hyperledger.fabric.contract.annotation.Contact;
import org.hyperledger.fabric.contract.annotation.Contract;
import org.hyperledger.fabric.contract.annotation.Default;
import org.hyperledger.fabric.contract.annotation.Info;
import org.hyperledger.fabric.contract.annotation.License;
import org.hyperledger.fabric.contract.annotation.Transaction;
import org.hyperledger.fabric.shim.ChaincodeStub;
import org.hyperledger.fabric.shim.ledger.KeyValue;
import org.hyperledger.fabric.shim.ledger.QueryResultsIterator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Contract(
        name = "myFirstChainCode",
        info = @Info(
                title = "MyFirstChainCode contract",
                description = "The hyperlegendary car contract",
                version = "0.0.1-SNAPSHOT",
                license = @License(
                        name = "Apache 2.0 License",
                        url = "http://www.apache.org/licenses/LICENSE-2.0.html"),
                contact = @Contact(
                        email = "f.carr@example.com",
                        name = "F Carr",
                        url = "https://hyperledger.example.com")))
@Default
public final class MyFirstChainCode implements ContractInterface {

    @Transaction()
    public void initUsers(final Context ctx) {
        ChaincodeStub stub = ctx.getStub();
        stub.putStringState("USER1", "{ \"name\": \"zhangsan\", \"gender\": \"male\", \"age\": \"28\" }");
        stub.putStringState("USER2", "{ \"name\": \"susan\", \"gender\": \"female\", \"age\": \"18\" }");
        stub.putStringState("USER3", "{ \"name\": \"lisi\", \"gender\": \"male\", \"age\": \"23\" }");
        stub.putStringState("USER4", "{ \"name\": \"lili\", \"gender\": \"female\", \"age\": \"25\" }");
    }

    @Transaction()
    public String queryUserById(final Context ctx, final String key) {
        ChaincodeStub stub = ctx.getStub();
        JSONObject jsonObject = JSON.parseObject(stub.getStringState(key));
        return jsonObject != null ? jsonObject.toJSONString() : "";
    }

    @Transaction()
    public String queryAllUsers(final Context ctx) {
        ChaincodeStub stub = ctx.getStub();
        final String startKey = "USER1";
        final String endKey = "USER4";
        List<JSONObject> queryResults = new ArrayList<>();
        QueryResultsIterator<KeyValue> results = stub.getStateByRange(startKey, endKey);
        for (KeyValue result: results) {
            queryResults.add(JSON.parseObject(result.getStringValue()));
        }
        return JSON.toJSONString(queryResults);
    }

    @Transaction()
    public String test(final Context ctx) {
        return "this is test method";
    }
}
